import {Directive, Input, Output, EventEmitter, ElementRef, HostListener} from "@angular/core";
import {ResponseMsgModel} from "../shared/model/response-msg-model";
import {CommonHelper} from "../../shared/helper/common-helper";
import {VerifyCommon} from "./verify-common";

@Directive({
    selector: "[passwordValidator]"
})
export class VerifyPasswordDirective extends VerifyCommon {
    @Input() passwordValidator: any[];
    @Output() verifyResponse: EventEmitter<ResponseMsgModel> = new EventEmitter<ResponseMsgModel>();

    constructor() {
        super();
    }

    /**
     * 当密码输入框失去焦点时校验输入框中的值。
     * 校验的情况有：
     * 1）不为空，为空返回false
     * 2）如果不为空，则校验密码位数不能少于6位或多于12位
     */
    @HostListener("blur") onBlur() {
        let password = CommonHelper.trim(this.passwordValidator[0]);
        if (!password) {
            this.responseComponent(false, "密码不能为空");
        } else {
            let length = password.length;
            if (length > 12 || length < 6) {
                this.responseComponent(false, "密码位数不能少于6位或多于12位")
            } else {
                this.responseComponent(true, "");
            }
        }

        let retryPassElem = this.passwordValidator[1],
            valInRetryPass = CommonHelper.trim(retryPassElem.value);
        if (valInRetryPass) {
            retryPassElem.focus();
            retryPassElem.blur();
        }
    }

    getResponseEmitter(): EventEmitter<ResponseMsgModel> {
        return this.verifyResponse;
    }
}